<template>
  <div class="diff-container" v-html="diffHtml" ref="diffContainer"></div>
</template>

<script lang="ts" setup>
import { ref, watch, nextTick } from 'vue'
import hljs from 'highlight.js'

interface Props {
  diffHtml: string
}

const props = defineProps<Props>()
const diffContainer = ref<HTMLElement>()

// 应用语法高亮
const applyHighlight = async () => {
  await nextTick()
  if (diffContainer.value) {
    // 查找所有代码块并应用语法高亮
    const codeBlocks = diffContainer.value.querySelectorAll('code, .d2h-code-line-ctn')
    codeBlocks.forEach((block) => {
      if (block.textContent && block.textContent.trim()) {
        try {
          hljs.highlightElement(block as HTMLElement)
        } catch (error) {
          // 如果高亮失败，忽略错误
          console.debug('语法高亮失败:', error)
        }
      }
    })
  }
}

// 监听 diffHtml 变化，重新应用语法高亮
watch(
  () => props.diffHtml,
  () => {
    if (props.diffHtml) {
      applyHighlight()
    }
  },
  { immediate: true },
)
</script>

<style scoped>
.diff-container {
  border-radius: 12px;
  overflow: hidden;
  border: 1px solid rgba(102, 126, 234, 0.1);
  background: #ffffff;
}

/* diff2html 样式覆盖 */
.diff-container :deep(.d2h-wrapper) {
  border: none;
  border-radius: 12px;
  overflow: hidden;
}

.diff-container :deep(.d2h-file-header) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 12px 16px;
  font-weight: 600;
}

.diff-container :deep(.d2h-file-stats) {
  color: rgba(255, 255, 255, 0.9);
}

.diff-container :deep(.d2h-code-side-line) {
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  font-size: 13px;
  line-height: 1.5;
}

.diff-container :deep(.d2h-ins) {
  background-color: rgba(46, 160, 67, 0.15);
  border-color: rgba(46, 160, 67, 0.4);
}

.diff-container :deep(.d2h-del) {
  background-color: rgba(203, 36, 49, 0.15);
  border-color: rgba(203, 36, 49, 0.4);
}

.diff-container :deep(.d2h-code-side-linenumber) {
  background: rgba(248, 250, 252, 0.8);
  border-color: rgba(102, 126, 234, 0.1);
  color: #666;
  font-size: 12px;
}

.diff-container :deep(.d2h-code-side-emptyplaceholder) {
  background: rgba(248, 250, 252, 0.5);
}

/* 语法高亮样式增强 */
.diff-container :deep(.hljs) {
  background: transparent !important;
  padding: 0 !important;
}

.diff-container :deep(.hljs-keyword) {
  color: #d73a49;
  font-weight: 600;
}

.diff-container :deep(.hljs-string) {
  color: #032f62;
}

.diff-container :deep(.hljs-comment) {
  color: #6a737d;
  font-style: italic;
}

.diff-container :deep(.hljs-number) {
  color: #005cc5;
}

.diff-container :deep(.hljs-function) {
  color: #6f42c1;
}

.diff-container :deep(.hljs-variable) {
  color: #e36209;
}

.diff-container :deep(.hljs-tag) {
  color: #22863a;
}

.diff-container :deep(.hljs-attr) {
  color: #6f42c1;
}

.diff-container :deep(.hljs-title) {
  color: #6f42c1;
  font-weight: 600;
}
</style>
